package com.atguigu.gmall.mq.receiver;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 监听普通消息
 *
 * @author: atguigu
 * @create: 2023-08-11 11:47
 */
@Slf4j
@Component
public class ConfimReceiver {

    /**
     * 消费者监听消息代码-目的：创建交换机且绑定到指定队列、消费消息
     *
     * @param msg     监听到消息内容，一定要生产者发送业务消息类型一致
     * @param channel 信道
     * @param message 消息对象
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = "exchange.confirm", durable = "true"),
            value = @Queue(value = "queue.confirm", durable = "true"),
            key = "routing.confirm"
    ))
    //@RabbitListener(queues = {"queue.confirm"}) //保证队列是存在，跟交换机进行了绑定
    public void receiverMsg(String msg, Channel channel, Message message) {
        if (StringUtils.isNotBlank(msg)) {
            log.info("[mq服务]receiverMsg监听到消息：{}", msg);
            //执行业务
            //消费者端手动应答,当broker收到应答后，才会将消息删除
            //basicAck成功应答，参数一：消息投递标签 数字自增 参数二：是否批量确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

            //channel.basicReject(); //拒绝消息，被拒绝消息可以进入死信队列
            //channel.basicNack();   //应答失败，参数三设置是否需要broker再次投递消息

        }
    }

}
